package com.tom.architect02.mnbase.net;

import java.io.IOException;

import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Added by Tom on 2024/05/20.
 */
public class OkHttpCall  implements Call {

    private ServiceMethod mServiceMethod;
    private static OkHttpClient client;

    static {
        client = new OkHttpClient(); // 单例的一种实现方式
    }
    public OkHttpCall(ServiceMethod serviceMethod) {
        this.mServiceMethod = serviceMethod;
    }

    // 同步请求
    @Override
    public String execute()   {
        if (mServiceMethod.getMethodName().equals("GET")) {
            Request request = new Request.Builder().url(mServiceMethod.getBaseUrl()).build();
            try {
                Response response = client.newCall(request).execute();
                return response.body().string();
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

//    @Override
//    public Response execute() throws IOException {
//        return null;
//    }

    // 异步请求
    @Override
    public void enqueue(Callback callback) {
        if (mServiceMethod.getMethodName().equals("GET")) {
            Request request = new Request.Builder()
                    .url(mServiceMethod.getBaseUrl())
                    .build();
            client.newCall(request).enqueue(new okhttp3.Callback() {
                @Override
                public void onFailure(okhttp3.Call call, IOException e) {
                    callback.onFailure(call,e);
                }

                @Override
                public void onResponse(okhttp3.Call call, Response response) throws IOException {
                    callback.onResponse(call,response);
                }
            });
        }
    }

}
